package com.hoyo.service;

import java.util.HashMap;
import java.util.List;

import org.apache.shiro.authc.UnknownAccountException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hoyo.common.AppConstant;
import com.hoyo.common.PageInfo;
import com.hoyo.domain.Movie;
import com.hoyo.domain.User;
import com.hoyo.domain.Catalog;
import com.hoyo.domain.CatalogCollect;
import com.hoyo.domain.CatalogReport;
import com.hoyo.mapper.CatalogMapper;
import com.hoyo.mapper.MovieMapper;
import com.hoyo.utils.HttpUrlConnectionUtils;
import com.hoyo.utils.TokenUtils;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;


@Service()
public class CatalogServiceImpl implements CatalogService{
	
	@Autowired
	private CatalogMapper catalogMapper;
	
	@Autowired
	private MovieMapper movieMapper;
	
	@Autowired
	private UserService userService;
	
	@Override
	public void saveCatalog(int userId, String catalog)  throws Exception{
		JSONObject object = new JSONObject(catalog);
		String catalogName = object.getString("catalogName");
		String introduction = object.getString("introduction");
		int catalogType = object.getInt("channelId");
		String catalgPoster = object.getString("catalgPoster");
		JSONArray movies = object.getJSONArray("movie");
		String catalogPoster = AppConstant.Qiniuyun.publicDomain +"/"+ catalgPoster;
		Catalog userCatalog = new Catalog(userId, catalogName, catalogPoster, introduction, catalogType);
		int affectLines = catalogMapper.save(userCatalog);
		System.out.println("affectLines or recordId ？："+affectLines);
		if(affectLines >= 1){
			for(int i=0; i<movies.length(); i++){
				JSONObject movie = movies.getJSONObject(i);
				String movieName = movie.getString("movieName");
				int sortNumber = movie.getInt("sortNumber");
				String resourceName = movie.getString("resourceName");
				String realPath = AppConstant.Qiniuyun.privateDomain + "/" + resourceName;
				Movie mv = new Movie(userCatalog.getId(), realPath, movieName, sortNumber);
				movieMapper.save(mv);
			}
		}
	}
	
	@Override
	public List<Catalog> findCatalogsByAccount(String account) throws Exception {
		return catalogMapper.findCatalogsByAccount(account);
	}
	
	@Override
	public List<Catalog> findCatalogsByAccountId(int accountId) throws Exception {
		// TODO Auto-generated method stub
		return catalogMapper.findCatalogsByAccountId(accountId);
	}

	@Override
	public PageInfo<Catalog> pageFindCatalogsByChecked(boolean isChecked, int pageNum, int pageSize) throws Exception{
		
		List<Catalog> catalogs = catalogMapper.findCatalogsByIsCheckedOrderByCreateTimeLimitBy(isChecked, (pageNum-1)*pageSize, pageSize);
		for (Catalog catalog : catalogs) {
			List<Movie> movies = movieMapper.findMoviesByCatalogId(catalog.getId());
			catalog.setMovies(movies);
		}
		int total = catalogs.size()>0?catalogs.get(0).getTotal():0;
		System.out.println(com.alibaba.fastjson.JSONObject.toJSONString(catalogs));
		return new PageInfo<>(pageNum, pageSize, total, catalogs);
	}

	@Override
	public void enabledCatalog2show(int id) throws Exception {
		catalogMapper.updateCatalogIsCheckedAndIsShowedById(id, true, true);
	}

	@Override
	public PageInfo<Catalog> pageFindCatalogs(int pageNum, int pageSize) throws Exception {
		List<Catalog> catalogs = catalogMapper.findCatalogsOrderByCreateTimeLimitBy((pageNum-1)*pageSize, pageSize);
		int total = catalogs.size()>0?catalogs.get(0).getTotal():0;
		return new PageInfo<>(pageNum, pageSize, total, catalogs);
	}

	@Override
	public PageInfo<Catalog> pageFindCatalogsByChannelId(int channelId, int pageNum, int pageSize) throws Exception {
		List<Catalog> catalogs = catalogMapper.findCatalogsByChannelIdOrderByCreateTimeLimitBy(channelId, (pageNum-1)*pageSize, pageSize);
		int total = catalogs.size()>0?catalogs.get(0).getTotal():0;
		return new PageInfo<>(pageNum, pageSize, total, catalogs);
	}

	@Override
	public PageInfo<Catalog> offLoadCatalog(int catalogId) throws Exception {
		catalogMapper.updateCatalogByIsShowedAndId(catalogId, false);
		return this.pageFindCatalogs(1, 5);
	}

	@Override
	public PageInfo<Catalog> removeCatalog(int catalogId) throws Exception {
		this.removeCouldResourceByCatalogId(catalogId);
		return this.pageFindCatalogs(1, 5);
	}
	
	private void removeCouldResourceByCatalogId(int catalogId) throws Exception{
//		1.查询所有相关的云资源信息，包括视频目录封面和视频链接的key值
		Catalog catalog = catalogMapper.findById(catalogId);
		List<Movie> movies = movieMapper.findMoviesByCatalogId(catalogId);
//		2.构建批删除操作
		String entry = "";
		StringBuilder builder = new StringBuilder();
//		2.1 视频目录封面
		if(catalog.getCatalogPoster()!=null && !"".equals(catalog.getCatalogPoster())){
			String catalogPoster = catalog.getCatalogPoster();
			System.out.println(catalogPoster.substring(catalogPoster.lastIndexOf("/")+1));
			entry = AppConstant.Qiniuyun.publicBucketName+":"+catalogPoster.substring(catalogPoster.lastIndexOf("/")+1);
			builder.append("op=/delete/"+UrlSafeBase64.encodeToString(entry)+"&");
		}
//		2.2 视频
		for (Movie movie : movies) {
			if(movie.getRealPath()!=null && !"".equals(movie.getRealPath())){
				String realPath = movie.getRealPath();
				System.out.println(realPath.substring(realPath.lastIndexOf("/")+1));
				entry = AppConstant.Qiniuyun.privateBucketName+":"+realPath.substring(realPath.lastIndexOf("/")+1);
				builder.append("op=/delete/"+UrlSafeBase64.encodeToString(entry)+"&");
			}
		}
//		3. 设置http连接配置
		String path = "http://rs.qiniu.com/batch";
		String contentType="application/x-www-form-urlencoded";
		String body = builder.toString();
		body = body.substring(0, body.length()-1);
		System.out.println(body);
//		3.1  生成资源管理授权码
		StringMap authorization = TokenUtils.authorization(path, body.getBytes(), contentType);
		System.out.println(authorization.get("Authorization"));
//		3.2 设置http请求头
		HashMap<String, Object> headers = new HashMap<>();
		headers.put("Content-Type", contentType);
		headers.put("Authorization", authorization.get("Authorization"));
//		3.3 发起请求
		byte[] result = HttpUrlConnectionUtils.openConnection(path, "POST", headers, body);
//		3.4 请求结果解析
		System.out.println(new String(result));
		String response = new String(result);
		if(response.contains("200")){
//			3.4.1 请求成功
			catalogMapper.deleteById(catalogId);
			movieMapper.removeByCatalogId(catalogId);
		}
	}

	@Override
	public PageInfo<Catalog> onLoadCatalog(int catalogId) throws Exception {
		catalogMapper.updateCatalogByIsShowedAndId(catalogId, true);
		return this.pageFindCatalogs(1, 5);
	}

	@Override
	public PageInfo<Catalog> pageSearch(String keyword, int pageNum, int pageSize) throws Exception {
		List<Catalog> catalogs = catalogMapper.findCatalogsByKeywordOrderByCreateTimeLimitBy("%"+keyword+"%", (pageNum-1)*pageSize, pageSize);
		int total = catalogs.size()>0?catalogs.get(0).getTotal():0;
		return new PageInfo<>(pageNum, pageSize, total, catalogs);
	}

	@Override
	public List<Catalog> findCatalogsByChannelsTypeAndSortByPlayAmount(int channelId, int start, int size)
			throws Exception {
		// TODO Auto-generated method stub
		return catalogMapper.findCatalogsByChannelsTypeAndSortByPlayAmount(channelId, start,size);
	}

	@Override
	public PageInfo<Catalog> pageFindCatalogsByChannelId(int channelId, int pageNum, int pagesize, int type)
			throws Exception {
		List<Catalog> catalogs = null;
		if(1==type){
			catalogs = catalogMapper.findCatalogsByChannelsTypeAndSortByDate(channelId, (pageNum-1)*pagesize, pagesize);
		}else{
			catalogs = catalogMapper.findCatalogsByChannelsTypeAndSortByPlayAmount(channelId, (pageNum-1)*pagesize, pagesize);
		}
		int total = catalogs.size()>0?catalogs.get(0).getTotal():0;
		return new PageInfo<Catalog>(pageNum, pagesize, total, catalogs);
	}

	@Override
	public void shoucangCatalogsById(CatalogCollect cc) throws Exception {
		// TODO Auto-generated method stub
		catalogMapper.shoucangCatalogsById(cc);
	}

	@Override
	public void cancelshoucangCatalogsById(int catalogId, int userId) throws Exception {
		// TODO Auto-generated method stub
		catalogMapper.cancelshoucangCatalogsById(catalogId, userId);
	}

	@Override
	public List<Catalog> findUserLikeCatalogByUserId(int userId) throws Exception {
		// TODO Auto-generated method stub
		return catalogMapper.findUserLikeCatalogByUserId(userId);
	}

	@Override
	public List<CatalogCollect> findUserisLikedCatalogByUserId(int catalogId, int userId) throws Exception {
		// TODO Auto-generated method stub
		return catalogMapper.findUserisLikedCatalogByUserId(catalogId, userId);
	}

	@Override
	public PageInfo<CatalogReport> pageFindCatalogReports(int pageNum, int pageSize) throws Exception{
		
		List<CatalogReport> reports = catalogMapper.findCatalogReportsLimitBy((pageNum-1)*pageSize, pageSize);
		for (CatalogReport catalogReport : reports) {
			List<Movie> movies = movieMapper.findMoviesByCatalogId(catalogReport.getCatalogId());
			catalogReport.setMovies(movies);
		}
		int total = reports.size()>0?reports.get(0).getTotal():0;
		return new PageInfo<>(pageNum, pageSize, total, reports);
	}

	@Override
	public PageInfo<CatalogReport> reportPass(int id, int catalogId) throws Exception {
		catalogMapper.updateCatalogReportByIdAndIsSolvedAndIsReally(id, true, true);
		this.removeCouldResourceByCatalogId(catalogId);
		return this.pageFindCatalogReports(1, 3);
	}

	@Override
	public PageInfo<CatalogReport> reportNotPass(int id) throws Exception {
		catalogMapper.updateCatalogReportByIdAndIsSolvedAndIsReally(id, true, false);
		return this.pageFindCatalogReports(1, 3);
	}

	@Override
	public void saveCatalogReport(CatalogReport cr) throws Exception {
		catalogMapper.saveCatalogReport(cr);
	}
}
